package com.tmpt.controller.action;


import com.opensymphony.xwork2.ActionSupport;
import com.tmpt.dto.*;
import com.tmpt.others.singleuser.OnlineUserBindingListener;
import com.tmpt.service.IMenuService;
import com.tmpt.service.IOperationlogService;
import com.tmpt.service.ISecurityV2Service;
import com.tmpt.utils.StringUtils;
import com.tmpt.utils.WebUtils;
import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@Scope("prototype")
public class SecurityV2Action extends ActionSupport{
	private Logger log = Logger.getLogger(this.getClass());

	private static final long serialVersionUID = 1L;
	private String menu1Id;
	private String menu1Name;
	private String menu2Id;
	private String menu2Name;
	private String menuFunName;
	private String accessTypeLevel;
	private String url;
	private String sort;
	//Role
	private String roleJsonArray;
	private String roleName;
	private String roleId;
	//USER
	private String userId;
	private String selectedRoleNodes;
	
	//邮箱验证码
	private String username;
	private String validateCode;
	
	private String result;
	private List<Map<String,Object>> jsonArrayResult;

	@Resource private ISecurityV2Service securityV2Service;
	@Resource private IOperationlogService operationlogService;
	@Resource private IMenuService menuService;
	private A1OperationlogDto oprDtoBack = new A1OperationlogDto(WebUtils.getRequest(), A1OperationlogDto.UserTypeBack);
	 
	public String addMenu1(){
		try{
			A2Menu1Dto menu1Dto = new A2Menu1Dto();
			menu1Dto.setSort(Integer.parseInt(sort));
			menu1Dto.setText(menu1Name);
			securityV2Service.addA2Menu1(menu1Dto, oprDtoBack);
			this.result = "成功";
		}catch (Exception e) {
			this.result = "出错";
			e.printStackTrace();
		}
		return "menu";
	}
	
	public String addMenu2(){
		try{
			A2Menu2Dto menu2Dto = new A2Menu2Dto();
			if(StringUtils.isNull(sort)){
				sort = "0";
			}
			menu2Dto.setSort(Integer.parseInt(sort));
			menu2Dto.setText(menu2Name);
			menu2Dto.setUrl(url);
			securityV2Service.addA2Menu2(Long.parseLong(menu1Id), menu2Dto, oprDtoBack);
			this.result = "成功";
		}catch (Exception e) {
			this.result = "出错";
			e.printStackTrace();
		}
		return "menu";
	}

	public String addMenuFun(){
		try{
			A2MenuFunctionDto menuFunDto = new A2MenuFunctionDto();
			menuFunDto.setText(menuFunName);
			menuFunDto.setAccessTypeLevel(Integer.parseInt(accessTypeLevel));
			menuFunDto.setUrl(url);
			securityV2Service.addA2MenuFunction(Long.parseLong(menu2Id), menuFunDto, oprDtoBack);
			this.result = "成功";
		}catch (Exception e) {
			this.result = "出错";
			e.printStackTrace();
		}
	
		return "menu";
	}
	

	/**
	 * Add a role
	 * @return
	 */
	public String addRole(){
		//[{"menuId":9,"menuParentId":0,"dataLimitType":0},{"menuId":10,"menuParentId":9,"dataLimitType":"0"},{"menuId":11,"menuParentId":10,"dataLimitType":0},
		// {"menuId":12,"menuParentId":10,"dataLimitType":0},{"menuId":1,"menuParentId":0,"dataLimitType":0},{"menuId":2,"menuParentId":1,"dataLimitType":0},
		// {"menuId":3,"menuParentId":2,"dataLimitType":"0"},{"menuId":4,"menuParentId":2,"dataLimitType":"0"}]
		//roleJsonArray
		try{
			System.out.println("roleJsonArray:" + roleJsonArray);
			System.out.println("roleId:" + roleId);
			Result resultObj = menuService.bindRole_Menu(Long.parseLong(roleId), roleJsonArray, oprDtoBack);
			this.result = "成功";
		}catch (Exception e) {
			this.result = "出错";
			e.printStackTrace();
		}

		return "jsonResult";
	}

	/*public String addRole(){
		//roleJsonArray
		//[{"menu1Id":1,"menu2Id":1,"accessTypeLevel":"0"},{"menu1Id":1,"menu2Id":1,"accessType":"write"},{"menu1Id":1,"menu2Id":1,"accessType":"secret"},{"menu1Id":1,"menu2Id":2,"accessType":"read"},{"menu1Id":1,"menu2Id":2,"accessType":"write"},{"menu1Id":1,"menu2Id":2,"accessType":"secret"}]
		Map<Long,Map<Long,Map<String,Object>>> menu1IdMap = new HashMap<Long, Map<Long,Map<String,Object>>>();
		try{
			//System.out.println("roleJsonArray:"+roleJsonArray);
			JSONArray jsonArray = new JSONArray(roleJsonArray);
			for(int i=0;i<jsonArray.length();i++){
				JSONObject jsonObject = jsonArray.optJSONObject(i);
				Long menu1Id = jsonObject.optLong("menu1Id");
				Long menu2Id = jsonObject.optLong("menu2Id");
				int accessTypeLevel = jsonObject.optInt("accessTypeLevel");
				int dataLimitType = jsonObject.optInt("dataLimitType");

				Map<Long,Map<String,Object>> menu2IdMap = menu1IdMap.get(menu1Id);
				if(menu2IdMap == null){
					menu2IdMap = new HashMap<Long,Map<String,Object>>();
					//2级菜单的属性
					Map<String,Object> attrMap = new HashMap<String, Object>();
					attrMap.put("accessTypeLevel", accessTypeLevel);
					attrMap.put("dataLimitType", dataLimitType);
					//2级菜单 添加属性
					menu2IdMap.put(menu2Id, attrMap);
					menu1IdMap.put(menu1Id, menu2IdMap);
				}else{
					Map<String,Object> attrMapExist = menu2IdMap.get(menu2Id);
					if(attrMapExist == null){
						//2级菜单的属性
						Map<String,Object> attrMap = new HashMap<String, Object>();
						attrMap.put("accessTypeLevel", accessTypeLevel);
						attrMap.put("dataLimitType", dataLimitType);
						//2级菜单 添加属性
						menu2IdMap.put(menu2Id, attrMap);
						continue;
					}
					int accessTypeLevelExist = (Integer)attrMapExist.get("accessTypeLevel");
					//当前访问级别更大，用这个做访问权限
					if(accessTypeLevelExist < accessTypeLevel){
						attrMapExist.put("accessTypeLevel", accessTypeLevel);
					}
					
				}
			}
			
			securityV2Service.bindRole_Menu(roleName, menu1IdMap, oprDtoBack);

			this.result = "成功";
		}catch (Exception e) {
			this.result = "出错";
			e.printStackTrace();
		}
		
		return "jsonResult";
	}*/

	public String queryMenus4RoleConfByRoleId(){
		try{
			//System.out.println("dddd");
			//Result resultObj = securityV2Service.queryMenus4RoleConfByRoleId(Long.parseLong(roleId));
			Result resultObj = menuService.queryMenus4RoleConfByRoleId(Long.parseLong(roleId));
			String menu4RoleConfByRoleIdJson = (String)resultObj.getResultMap().get("menu4RoleConfByRoleIdJson");
			this.result = menu4RoleConfByRoleIdJson;
		}catch (Exception e) {
			this.result = "出错";
			e.printStackTrace();
		}
		return "jsonResult";
	}
	



	/**
	 * 查询用户所拥有的角色列表
	 * @return
	 */
	public String queryRoleListByUserid(){
		Result result = new Result();
		try {
			//System.out.println("------------userId-"+userId);
			Result<A2RoleDto> resultObj = securityV2Service.queryA2RoleList();
			Result<A2RoleDto> resultObjMy = securityV2Service.queryA2RoleListByUser(Long.parseLong(userId));
			if(!resultObj.isSuccess()){
				return "";
			}
			List<A2RoleDto> roleDtoList = resultObj.getResultList();
			
			List<A2RoleDto> roleDtoListMy = resultObjMy.getResultList();
			List<Long> roleDtoListMyLong = new ArrayList<Long>();
			for(A2RoleDto roleDtoMy:roleDtoListMy){
				roleDtoListMyLong.add(roleDtoMy.getId());
			}
			//System.out.println("-=============:"+roleDtoListMy);
			
			this.jsonArrayResult = new ArrayList<Map<String,Object>>();
			//JSONArray jsonArr = new JSONArray();
			for(A2RoleDto roleDto : roleDtoList){
				//JSONObject jo = new JSONObject();
				Map<String,Object> jo = new HashMap<String, Object>();
				jo.put("id", roleDto.getId());
				jo.put("text", roleDto.getRoleName());
				if(roleDtoListMyLong.contains(roleDto.getId())){
					jo.put("checked", "true");
				}
				this.jsonArrayResult.add(jo);
			}
			//System.out.println("----------------"+jsonArr.toString());

		}catch (Exception e) {
			e.printStackTrace();
			this.result = "操作失败："+e.getLocalizedMessage();
			result.fault("系统出错:" + e.getLocalizedMessage());
		}
		return "jsonArray";
	}

	/**
	 * 更新用户角色列表
	 * @return
	 */
	public String updateRoleListByUserid(){
		Result result = new Result();
		try {
			//System.out.println("------------userId-"+userId);
			//System.out.println("------------selectedRoleNodes-"+selectedRoleNodes);//[1,6]
			JSONArray jarr = new JSONArray(selectedRoleNodes);
			List<Long> roleIdList = new ArrayList<Long>();
			for(int i=0;i<jarr.length();i++){
				roleIdList.add(Long.valueOf(jarr.getInt(i)));
			}
			
			securityV2Service.bindUser_Role(Long.parseLong(userId), roleIdList, oprDtoBack);

	    	this.result = "成功";
		}catch (Exception e) {
			e.printStackTrace();
			this.result = "操作失败："+e.getLocalizedMessage();
			result.fault("系统出错:"+e.getLocalizedMessage());
		}
		return "jsonResult";
	}
	

	/**
	 * 不用权限，直接放行的标识：_access
	 * @return
	 */
	public String getCompanyDeptTree_access(){
		Result resultObj = new Result();
		try {
			resultObj = securityV2Service.queryA2CompnayList(null);
			List<A2CompanyDto> a2CompanyDtoList = resultObj.getResultList();
			
			this.jsonArrayResult = new ArrayList<Map<String,Object>>();
			for(A2CompanyDto companyDto:a2CompanyDtoList){
				String companyId = String.valueOf(companyDto.getId());
				String companyName = companyDto.getName();
				Map<String, Object> joCompany = new HashMap<String, Object>();
				joCompany.put("id", "c"+companyId);
				joCompany.put("text", companyName);

				List<Map<String,Object>> jarrDept = new ArrayList<Map<String,Object>>();
				for(A2DeptDto deptDto:companyDto.getA2DeptDtoList()){
					String deptId = String.valueOf(deptDto.getId());
					String deptName = deptDto.getName();
					Map<String, Object> joDept = new HashMap<String, Object>();
					//JSONObject joDept = new JSONObject();
					joDept.put("id", deptId);
					joDept.put("text", deptName);
					jarrDept.add(joDept);
				}
				joCompany.put("children", jarrDept);
				this.jsonArrayResult.add(joCompany);
			}
			
			String json = this.jsonArrayResult.toString();
			//System.out.println("==================:"+json);

	    	this.result = json;
		}catch (Exception e) {
			e.printStackTrace();
			this.result = "操作失败："+e.getLocalizedMessage();
		}
		return "jsonArray";
	}

	

    /**
	 * 电子邮箱校验
	 * @return
	 */
	public String emailValidate(){
		oprDtoBack.setLogTypeName("登录[后台]");
		try {
			HttpServletRequest request = WebUtils.getRequest();
			HttpSession session = request.getSession();
			String emailValidateCode = this.validateCode;
			String emailValidateCodeSession = (String)session.getAttribute("randStr");
			
			/*
			if(!emailValidateCode.equalsIgnoreCase(emailValidateCodeSession)){
				this.result = "电子邮箱校验码错误，请重新登录！";
				oprDtoBack.setDescription("登录名:"+username+":"+this.result);
				operationLogService.addOperationlog(oprDtoBack);
				return "indexBefore1";
			}
			*/
			
			//登录成功
			session.setAttribute("onlineUserBindingListener", new OnlineUserBindingListener(username));

			return "index";
		} catch (Exception e) {
			e.printStackTrace();
			this.result = e.getLocalizedMessage();
			oprDtoBack.setDescription("登录名:" + username + ":" + this.result);
			operationlogService.addOperationlog(oprDtoBack);
			return "indexBefore1";
		}
	}

	/*
	public String getCompanyDeptTree(){
		Result resultObj = new Result();
		try {
			System.out.println("------------getCompanyDeptTree-");

			resultObj = securityV2Service.queryA2CompnayList(null);
			List<A2CompanyDto> a2CompanyDtoList = resultObj.getResultList();
			this.jsonArrayResult = new JSONArray();
			for(A2CompanyDto companyDto:a2CompanyDtoList){
				String companyId = String.valueOf(companyDto.getId());
				String companyName = companyDto.getName();
				JSONObject joCompany = new JSONObject();
				joCompany.put("id", "c"+companyId);
				joCompany.put("text", companyName);

				JSONArray jarrDept = new JSONArray();
				for(A2DeptDto deptDto:companyDto.getA2DeptDtoList()){
					String deptId = String.valueOf(deptDto.getId());
					String deptName = deptDto.getName();
					JSONObject joDept = new JSONObject();
					joDept.put("id", deptId);
					joDept.put("text", deptName);
					jarrDept.put(joDept);
				}
				joCompany.put("children", jarrDept);
				this.jsonArrayResult.put(joCompany);
			}
			
			String json = this.jsonArrayResult.toString();
			System.out.println("==================:"+json);

	    	this.result = json;
		}catch (Exception e) {
			e.printStackTrace();
			this.result = "操作失败："+e.getLocalizedMessage();
		}
		return "jsonArray";
	}
	*/

	
	
	
	public Logger getLog() {
		return log;
	}
	public void setLog(Logger log) {
		this.log = log;
	}
	public String getMenu1Name() {
		return menu1Name;
	}
	public void setMenu1Name(String menu1Name) {
		this.menu1Name = menu1Name;
	}
	public String getSort() {
		return sort;
	}
	public void setSort(String sort) {
		this.sort = sort;
	}
	public String getResult() {
		return result;
	}
	public void setResult(String result) {
		this.result = result;
	}
	public ISecurityV2Service getSecurityV2Service() {
		return securityV2Service;
	}
	public void setSecurityV2Service(ISecurityV2Service securityV2Service) {
		this.securityV2Service = securityV2Service;
	}
	public A1OperationlogDto getOprDtoBack() {
		return oprDtoBack;
	}
	public void setOprDtoBack(A1OperationlogDto oprDtoBack) {
		this.oprDtoBack = oprDtoBack;
	}
	public static long getSerialversionuid() {
		return serialVersionUID;
	}
	public String getMenu1Id() {
		return menu1Id;
	}
	public void setMenu1Id(String menu1Id) {
		this.menu1Id = menu1Id;
	}
	public String getMenu2Id() {
		return menu2Id;
	}
	public void setMenu2Id(String menu2Id) {
		this.menu2Id = menu2Id;
	}
	public String getMenu2Name() {
		return menu2Name;
	}
	public void setMenu2Name(String menu2Name) {
		this.menu2Name = menu2Name;
	}
	public String getUrl() {
		return url;
	}
	public void setUrl(String url) {
		this.url = url;
	}
	public String getMenuFunName() {
		return menuFunName;
	}
	public void setMenuFunName(String menuFunName) {
		this.menuFunName = menuFunName;
	}

	public String getRoleJsonArray() {
		return roleJsonArray;
	}

	public void setRoleJsonArray(String roleJsonArray) {
		this.roleJsonArray = roleJsonArray;
	}

	public String getRoleName() {
		return roleName;
	}

	public void setRoleName(String roleName) {
		this.roleName = roleName;
	}

	public String getAccessTypeLevel() {
		return accessTypeLevel;
	}

	public void setAccessTypeLevel(String accessTypeLevel) {
		this.accessTypeLevel = accessTypeLevel;
	}

	public String getRoleId() {
		return roleId;
	}

	public void setRoleId(String roleId) {
		this.roleId = roleId;
	}

	public String getUserId() {
		return userId;
	}

	public void setUserId(String userId) {
		this.userId = userId;
	}

	public String getSelectedRoleNodes() {
		return selectedRoleNodes;
	}

	public void setSelectedRoleNodes(String selectedRoleNodes) {
		this.selectedRoleNodes = selectedRoleNodes;
	}

	public List<Map<String, Object>> getJsonArrayResult() {
		return jsonArrayResult;
	}

	public void setJsonArrayResult(List<Map<String, Object>> jsonArrayResult) {
		this.jsonArrayResult = jsonArrayResult;
	}

	public String getValidateCode() {
		return validateCode;
	}

	public void setValidateCode(String validateCode) {
		this.validateCode = validateCode;
	}

	
	
	
}
